<template>
  <div class="upload_image_box" :class="size ? 'upload_' + size : ''">
    <el-upload :action="COMMONFILEUPLOAD" :disabled="disabled" v-if="!pics || pics.length <= 0 || pics.length < Number(limit)" list-type="picture-card" :show-file-list="false" :limit="Number(limit)" :headers="uploadHeaders" :accept="accept" :before-upload="beforeUpload" :on-success="onSuccess">
      <template>
        <i class="el-icon-plus" v-if="!$slots.inner" />
        <slot name="inner" />
      </template>
      <div slot="tip" class="upload_tip" v-if="tip">{{ tip }}</div>
    </el-upload>
    <div class="image_list">
      <div class="image_cell" v-for="(item, index) in pics" :key="index">
        <el-image class="el_image" :src="item.url" :preview-src-list="[item.url]">
        </el-image>
        <div class="icon_list">
          <i class="el-icon-zoom-in" @click="previewImage(item)"></i>
          <i class="el-icon-delete" v-if="!disabled" @click="removeImage(item)"></i>
        </div>
        <div class="blk"></div>
      </div>
    </div>
  </div>
</template>
<script>
import { api as viewerApi } from "v-viewer";
import "viewerjs/dist/viewer.css";
import { BASEURL, COMMONFILEUPLOAD } from "@/http/system";
import { deepClone } from '@/common/util';
import * as imageConversion from 'image-conversion';
import { COMPRESS_RATE } from '@/common/constants'
export default {
  name: "ImageUpload",
  props: {
    limit: {
      type: [Number, String],
      default: 1,
    },
    value: {
      type: Array,
      default: function () {
        return [];
      },
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    size: {
      type: String,
      default: "", // small  large
    },
    tip: {
      type: [String, Number],
      default: "",
    },
    accept: {
      type: String,
      default: ".jpg,.png,.jpeg",
    },
  },
  data() {
    return {
      pics: [],
      uploadHeaders: {},
      imageList: [],
      COMMONFILEUPLOAD,
    };
  },
  watch: {
    value: {
      handler: function (n, o) {
        let arr = [];
        console.log(n)
        if (n && n.length > 0) {
          n.map((k) => {
            let _type = typeof k;
            console.log(_type)
            if (_type == "string") {
              arr.push({
                name: k,
                path: k,
                url: BASEURL + k,
              });
            } else {
              arr.push(k);
            }
          });
        }
        
        this.pics = arr || [];
      },
      immediate: true,
    },
  },
  created() {
    let token = sessionStorage.getItem("token");
    this.uploadHeaders = { Authorization: token };
  },
  methods: {
    /** 监听文件上传成功 */
    onSuccess(response, file, fileList) {
      if (response.code == 200) {
        // const n = {};
        // n.name = response.data;
        // n.url = BASEURL + response.data;
        // n.path = response.data;
        // this.pics.push(n);
        let list = deepClone(this.value || [])
        list.push(response.data)
        this.$emit("input", list);
        this.$emit("change", list);
      }
    },

    // 预览图片
    previewImage(row) {
      this.imageList = [row.url];
      viewerApi({
        images: this.imageList,
        options: {
          zIndex: 99999,
        },
      });
    },

    // 删除图片
    removeImage(row) {
      let arr = []
      let list = deepClone(this.pics)
      this.imageList = [];
      let _nlist = list.filter((k) => k.path != row.path);
      _nlist.map(k => {
        arr.push(k.path)
      })
      console.log(arr)
      this.$emit("input", arr);
    },

    // 监听文件上传前
    beforeUpload(file) {
      console.log(file)
      return new Promise((resolve, reject) => {
        imageConversion.compress(file, COMPRESS_RATE).then(res => {
          console.log(res)
          res = new File([res], file.name, { type: res.type, lastModified: Date.now() })
          resolve(res)
        })
      })
    }


  },
};
</script>
<style lang="scss" scoped>
.upload_image_box {
  display: flex;

  .upload_tip {
    color: #999;
    font-size: 12px;
  }

  .image_list {
    display: flex;
    flex-wrap: wrap;
    margin-left:10px;

    .image_cell {
      position: relative;
      width: 148px;
      height: 148px;
      border: 1px dashed #d8d8d8;
      border-radius: 4px;
      padding: 2px;
      box-sizing: border-box;
      margin: 0 10px 10px 0;

      .icon_list {
        display: none;
        position: absolute;
        left: 0;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        text-align: center;
        z-index: 3;

        i {
          font-size: 24px;
          color: #fff;
          margin: 0 10px;
          cursor: pointer;
        }
      }

      .el_image {
        width: 100%;
        height: 100%;
        border-radius: 4px;
      }

      .blk {
        display: none;
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        right: 0;
        background: #000;
        opacity: 0.4;
        z-index: 2;
      }
    }

    .image_cell:hover {
      .icon_list {
        display: block;
      }

      .blk {
        display: block;
      }
    }
  }
}

.upload_small {
  ::v-deep .el-upload {
    width: 100px;
    height: 100px;
    line-height: 100px;
  }

  ::v-deep .image_list {
    .image_cell {
      width: 100px;
      height: 100px;
    }
  }
}
</style>